package ev.selection;

import ev.data.*;//need to add this line

import java.util.*;

public class Tournament implements Selection{

	public Population select(Population old, int limit)
	{
		int maxk = old.getPopulationSize()-limit;
		int mink = 5;
		int k, id;
		Random r = new Random();
		//Suppose minimum k is 5
		Population res = new Population(old.getCities());
		while(res.getPopulationSize()<limit){
			k = r.nextInt(maxk-mink+1)+mink;
			int oldsize = old.getPopulationSize();
			boolean[] flag = new boolean[oldsize];
			int index = r.nextInt(oldsize);
			Individual minQuality = old.getIndividual(index);
			flag[index] = true;
			for(int i = 1; i < k; i++){
				id = r.nextInt(oldsize);
				if(flag[id]){
					i--;
				}
				else{
					flag[id] = true;
					if(minQuality.getQuality() > old.getIndividual(id).getQuality()){
						minQuality = old.getIndividual(id);
						index = id;
					}
				}
			}
			old.remove(index);
			res.add(minQuality);			
		}
		return res;
	}
}